import os

from PIL import ImageQt
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import Qt, QUrl
from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QPixmapCache
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtWidgets import (QWidget, QHBoxLayout, QLabel, QComboBox, QSpinBox, QTableWidget, QTableWidgetItem,
                             QPushButton, QHeaderView, QMessageBox, QDialog, QTextEdit, QCheckBox)
from docx.shared import Inches

from database import search_questions, create_exam
from questiot_dialog import QuestionDetailDialog

QPixmapCache.setCacheLimit(10240)
import logging
from docx import Document
logging.basicConfig(level=logging.DEBUG)

class PaperCreateWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        # 新增计数标签属性
        self.question_count_label = QLabel("当前题目数量: 0")
        self.init_ui()
        self.selected_questions = []  # 临时存储选中的题目
        self.selected_question_ids = set()  # 临时存储选中的题目ID


    def init_ui(self):
        layout = QVBoxLayout()

        # 搜索条件
        self.search_panel = QWidget()
        search_layout = QHBoxLayout()

        self.type_combo = QComboBox()
        self.type_combo.addItems(["", "选择题", "填空题", "判断题", "综合题"])

        self.difficulty_combo = QComboBox()
        self.difficulty_combo.addItems(["", "1", "2", "3", "4", "5"])

        self.tags_input = QLineEdit()
        self.search_btn = QPushButton("搜索题目")
        self.search_btn.clicked.connect(self.load_questions)

        search_layout.addWidget(QLabel("题型:"))
        search_layout.addWidget(self.type_combo)
        search_layout.addWidget(QLabel("难度:"))
        search_layout.addWidget(self.difficulty_combo)
        search_layout.addWidget(QLabel("标签:"))
        search_layout.addWidget(self.tags_input)
        search_layout.addWidget(self.search_btn)
        self.search_panel.setLayout(search_layout)

        self.question_table = QTableWidget()
        self.question_table.setColumnCount(7)
        self.question_table.setHorizontalHeaderLabels(["选择", "ID", "题型", "题目", "图片", "答案", "图片"])
        self.question_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # 列宽设置
        header = self.question_table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Fixed)  # 选择列
        header.setSectionResizeMode(1, QHeaderView.Fixed)  # ID列
        header.setSectionResizeMode(2, QHeaderView.Fixed)  # 题型列
        header.setSectionResizeMode(4, QHeaderView.Fixed)  # 题型列
        header.setSectionResizeMode(6, QHeaderView.Fixed)  # 题型列
        self.question_table.setColumnWidth(0, 70)
        self.question_table.setColumnWidth(1, 100)
        self.question_table.setColumnWidth(2, 80)
        self.question_table.setColumnWidth(4, 60)
        self.question_table.setColumnWidth(6, 60)
        header.setSectionResizeMode(3, QHeaderView.Stretch)  # 题目列自动拉伸
        header.setSectionResizeMode(5, QHeaderView.Stretch)  # 题目列自动拉伸

        # 控制面板
        control_panel = QHBoxLayout()
        self.add_to_paper_btn = QPushButton("添加到试卷")
        self.add_to_paper_btn.clicked.connect(self.add_to_paper)
        self.preview_btn = QPushButton("预览试卷")
        self.preview_btn.clicked.connect(self.preview_paper)
        self.generate_btn = QPushButton("生成试卷")
        self.generate_btn.clicked.connect(self.generate_paper)

        # 修改控制面板布局
        control_panel.addWidget(self.question_count_label)  # 替换原spinbox的位置
        control_panel.addStretch()
        control_panel.addWidget(self.add_to_paper_btn)
        control_panel.addWidget(self.preview_btn)
        control_panel.addWidget(self.generate_btn)

        layout.addWidget(self.search_panel)
        layout.addWidget(self.question_table)
        layout.addLayout(control_panel)
        self.setLayout(layout)
        # 添加提示标签
        self.tip_label = QLabel("留空所有条件将显示全部题目")
        self.tip_label.setStyleSheet("color: #666; font-style: italic;")
        layout.insertWidget(1, self.tip_label)
        # 设置表格行高自适应
        self.question_table.resizeRowsToContents()
        # 添加表格提示
        self.question_table.setToolTip("双击任意单元格查看详情")
        self.question_table.itemDoubleClicked.connect(self.show_question_detail)

        self.selected_questions = []  # 临时存储选中的题目
        self.selected_question_ids = set()  # 临时存储选中的题目ID

    def add_to_paper(self):
        selected = []
        for row in range(self.question_table.rowCount()):
            if self.question_table.item(row, 0).checkState() == Qt.Checked:
                question_id = self.question_table.item(row, 1).text()
                # 检查是否已存在
                if question_id in self.selected_question_ids:
                    continue  # 跳过已选中的题目
                question_type = self.question_table.item(row, 2).text()
                content = self.question_table.item(row, 3).text()
                content_image = self.question_table.cellWidget(row, 4).pixmap().copy() if self.question_table.cellWidget(row, 4) else None
                answer = self.question_table.item(row, 5).text()
                answer_image = self.question_table.cellWidget(row, 6).pixmap().copy() if self.question_table.cellWidget(row, 6) else None

                selected.append({
                    'id': question_id,
                    'question_type': question_type,
                    'content': content,
                    'content_image': content_image,
                    'answer': answer,
                    'answer_image': answer_image,

                })
                self.selected_question_ids.add(question_id)

        if not selected:
            QMessageBox.warning(self, "警告", "未发现新增的题目！")
            return

        self.selected_questions.extend(selected)
        QMessageBox.information(self, "成功", f"已添加 {len(selected)} 道题目到试卷")
        # 新增：更新题目数量显示
        self.question_count_label.setText(f"当前题目数量: {len(self.selected_questions)}")

    def preview_paper(self):
        if not self.selected_questions:
            QMessageBox.warning(self, "警告", "当前没有题目可以预览！")
            return

        dialog = PaperPreviewDialog(self.selected_questions, self)
        if dialog.exec_() == QDialog.Accepted:
            # 更新为新的顺序
            self.selected_questions = dialog.new_order  # 新增此行
            self.question_count_label.setText(f"当前题目数量: {len(self.selected_questions)}")

    def load_questions(self):
        # 获取筛选条件（允许为空）
        criteria = {
            'type': self.type_combo.currentText() or None,
            'difficulty': self.difficulty_combo.currentText() or None,
            'tags': self.tags_input.text().strip() or None
        }

        # 执行查询（自动处理空条件）
        self.questions = search_questions(criteria if any(criteria.values()) else None)

        # # 显示提示信息
        # if not any(criteria.values()):
        #     QMessageBox.information(self, "提示", "当前显示全部题目，共{}道".format(len(self.questions)))

        self.question_table.setRowCount(len(self.questions))
        for row, q in enumerate(self.questions):
            # 添加复选框
            checkbox = QTableWidgetItem()
            checkbox.setCheckState(Qt.Checked if q['id'] in self.selected_question_ids else Qt.Unchecked)
            checkbox.setTextAlignment(Qt.AlignCenter)
            self.question_table.setItem(row, 0, checkbox)

            # 显示内容
            self.question_table.setItem(row, 1, QTableWidgetItem(q['id']))
            self.question_table.setItem(row, 2, QTableWidgetItem(q['question_type']))
            self.question_table.setItem(row, 3, QTableWidgetItem(q['content']))
            # 显示图片
            if q['content_image']:
                pixmap = QPixmap(q['content_image'])
                label = QLabel()
                label.setPixmap(pixmap.scaled(100, 100, Qt.KeepAspectRatio))
                self.question_table.setCellWidget(row, 4, label)

            self.question_table.setItem(row, 5, QTableWidgetItem(q['answer']))
            # 答案图片
            if q['answer_image']:
                pixmap = QPixmap(q['answer_image'])
                label = QLabel()
                label.setPixmap(pixmap.scaled(100, 100, Qt.KeepAspectRatio))
                self.question_table.setCellWidget(row, 6, label)

            # 分值输入
            spin = QSpinBox()
            spin.setRange(1, 100)
            spin.setValue(10)  # 默认分值
            self.question_table.setCellWidget(row, 7, spin)

    def show_question_detail(self, item):
        """显示题目详情"""
        row = item.row()
        question_data = self.questions[row]
        if question_data:
            dialog = QuestionDetailDialog(question_data, self)
            dialog.exec_()

    def generate_paper(self):
        if not self.selected_questions:
            QMessageBox.warning(self, "警告", "当前没有题目可以生成试卷！")
            return
        try:
            # 获取所有题型
            question_types = list(set(q['question_type'] for q in self.selected_questions))
            # 弹出配置对话框
            dialog = ExamConfigDialog(question_types, self)
            if dialog.exec_() != QDialog.Accepted:
                return
            # 应用分数配置
            config_scores = {t: dialog.type_scores[t].value() for t in question_types}
            for q in self.selected_questions:
                q['score'] = config_scores[q['question_type']]  # 按题型统一设置分数

            # 获取试卷名称
            exam_name = dialog.name_input.text().strip()
            if not exam_name:
                QMessageBox.warning(self, "警告", "请输入试卷名称！")
                return

            # 创建试卷
            exam_id = create_exam(exam_name, self.selected_questions)
            QMessageBox.information(self, "成功", f"试卷创建成功！ID: {exam_id}")

            # 清空数据
            self.selected_questions = []
            self.selected_question_ids.clear()
            self.question_count_label.setText("当前题目数量: 0")

        except Exception as e:
            QMessageBox.critical(self, "错误", f"创建失败: {str(e)}")


class PaperPreviewDialog(QDialog):
    def __init__(self, questions, parent=None):
        super().__init__(parent)
        self.new_order = None  # 新增结果存储属性
        self.original_questions = questions  # 保留原始数据
        self.questions = questions.copy()
        self.init_ui()
        self.load_data()
        self.last_operation_time = 0  # 操作时间戳

    def init_ui(self):
        self.setWindowTitle("试卷预览")
        self.setMinimumSize(800, 600)
        layout = QVBoxLayout()

        # 表格设置
        self.table = QTableWidget()
        self.table.setColumnCount(6)  # 增加操作列
        self.table.setHorizontalHeaderLabels(["题目", "图片", "答案", "答案图", "上移", "下移"])

        # 列宽设置
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(4, QHeaderView.Fixed)
        self.table.horizontalHeader().setSectionResizeMode(5, QHeaderView.Fixed)
        self.table.setColumnWidth(4, 60)
        self.table.setColumnWidth(5, 60)
        # 连接单元格点击事件
        self.table.cellClicked.connect(self.handle_cell_click)

        layout.addWidget(self.table)

        # 新增预览区域
        self.preview_area = QTextEdit()
        self.preview_area.setReadOnly(True)
        self.preview_area.setStyleSheet("font-size: 14px; background-color: #f9f9f9;")
        layout.addWidget(self.preview_area)

        # 底部按钮
        btn_box = QHBoxLayout()
        self.preview_btn = QPushButton("整体预览")  # 新增预览按钮
        self.preview_btn.clicked.connect(self.show_preview)
        self.save_btn = QPushButton("保存顺序")
        self.save_btn.clicked.connect(self.save_changes)
        self.cancel_btn = QPushButton("关闭")
        self.cancel_btn.clicked.connect(self.reject)
        btn_box.addStretch()
        btn_box.addWidget(self.preview_btn)  # 将预览按钮添加到布局中
        btn_box.addWidget(self.save_btn)
        btn_box.addWidget(self.cancel_btn)
        layout.addLayout(btn_box)
        self.setLayout(layout)

    def load_data(self):
        self.table.setRowCount(len(self.questions))

        for row, q in enumerate(self.questions):
            # 题目内容
            self.table.setItem(row, 0, QTableWidgetItem(q['content']))
            # 题目图片（带缩放比例保持）
            if isinstance(q['content_image'], QPixmap):  # 判断是否为 QPixmap 对象
                label = QLabel()
                label.setPixmap(q['content_image'].scaled(200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation))
                self.table.setCellWidget(row, 1, label)
            else:
                self.table.setCellWidget(row, 1, None)
            # 答案
            self.table.setItem(row, 2, QTableWidgetItem(q['answer']))
            # 答案图片
            if isinstance(q['answer_image'], QPixmap):  # 判断是否为 QPixmap 对象
                label = QLabel()
                label.setPixmap(q['answer_image'].scaled(200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation))
                self.table.setCellWidget(row, 3, label)
            else:
                self.table.setCellWidget(row, 3, None)

            self.add_operation_buttons(row)

    def show_preview(self):
        """显示整体预览"""
        preview_text = ""
        for idx, q in enumerate(self.questions, start=1):
            preview_text += f"<b>第 {idx} 题：</b><br>"
            preview_text += f"<b>题型：</b>{q['question_type']}<br>"
            preview_text += f"<b>题目：</b>{q['content']}<br>"

            # 处理题目图片
            if q['content_image']:
                # 将QPixmap转换为Base64
                pixmap = q['content_image']
                byte_array = QtCore.QByteArray()
                buffer = QtCore.QBuffer(byte_array)
                buffer.open(QtCore.QIODevice.WriteOnly)
                pixmap.save(buffer, "PNG")
                base64_data = byte_array.toBase64().data().decode()
                preview_text += f'<img src="data:image/png;base64,{base64_data}" width="200"><br>'

            preview_text += f"<b>答案：</b>{q['answer']}<br>"

            # 处理答案图片
            if q['answer_image']:
                # 将QPixmap转换为Base64
                pixmap = q['answer_image']
                byte_array = QtCore.QByteArray()
                buffer = QtCore.QBuffer(byte_array)
                buffer.open(QtCore.QIODevice.WriteOnly)
                pixmap.save(buffer, "PNG")
                base64_data = byte_array.toBase64().data().decode()
                preview_text += f'<img src="data:image/png;base64,{base64_data}" width="200"><br>'

        self.preview_area.setHtml(preview_text)
    def handle_cell_click(self, row, col):
        """处理操作列点击"""
        if col != 4:  # 仅处理操作列点击
            return

        # 防误触：300ms间隔
        current_time = QtCore.QTime.currentTime().msec()
        if current_time - self.last_click_time < 300:
            return
        self.last_click_time = current_time

        # 获取点击位置判断上下
        rect = self.table.visualItemRect(self.table.item(row, 4))
        pos = self.table.viewport().mapFromGlobal(QtGui.QCursor.pos())
        click_y = pos.y() - rect.y()

        # 上半区上移，下半区下移
        if click_y < rect.height() / 2 and row > 0:
            self.swap_rows(row, row - 1)
        elif click_y >= rect.height() / 2 and row < self.table.rowCount() - 1:
            self.swap_rows(row, row + 1)

    def swap_rows(self, src, dst):
        """交换行数据并刷新视图"""
        # 交换数据层
        self.questions[src], self.questions[dst] = self.questions[dst], self.questions[src]

        # 局部刷新避免重载整个表格
        temp_data = []
        for col in range(self.table.columnCount()):
            # 保存原数据
            temp = {
                'item': self.table.takeItem(src, col),
                'widget': self.table.cellWidget(src, col)
            }
            temp_data.append(temp)

            # 移动目标行数据到源行
            self.table.setItem(src, col, self.table.takeItem(dst, col))
            self.table.setCellWidget(src, col, self.table.cellWidget(dst, col))

            # 恢复源数据到目标行
            self.table.setItem(dst, col, temp_data[col]['item'])
            self.table.setCellWidget(dst, col, temp_data[col]['widget'])

        # 刷新行高
        self.table.resizeRowToContents(src)
        self.table.resizeRowToContents(dst)

        # 保持选中状态
        self.table.selectRow(dst if dst > src else src - 1)

    def add_operation_buttons(self, row):
        """为每行添加操作按钮"""
        # 上移按钮
        btn_up = QPushButton("↑")
        btn_up.setStyleSheet("min-width:30px; max-width:30px;")
        btn_up.clicked.connect(lambda _, r=row: self.move_row(r, "up"))
        self.table.setCellWidget(row, 4, btn_up)

        # 下移按钮
        btn_down = QPushButton("↓")
        btn_down.setStyleSheet("min-width:30px; max-width:30px;")
        btn_down.clicked.connect(lambda _, r=row: self.move_row(r, "down"))
        self.table.setCellWidget(row, 5, btn_down)

    def move_row(self, row, direction):
        """处理行移动"""
        # 防误触检查（500ms间隔）
        current_time = QtCore.QTime.currentTime().msecsSinceStartOfDay()
        if current_time - self.last_operation_time < 500:
            return
        self.last_operation_time = current_time

        new_index = row - 1 if direction == "up" else row + 1

        # 边界检查
        if new_index < 0 or new_index >= len(self.questions):
            return

        # 执行交换
        self.questions[row], self.questions[new_index] = self.questions[new_index], self.questions[row]

        # 完全重新加载数据保证显示正确
        self.load_data()
        self.table.selectRow(new_index)  # 保持选中状态

    def save_changes(self):
        new_order_questions = [q.copy() for q in self.questions]
        # 返回新顺序给父窗口
        self.new_order = new_order_questions  # 新增属性存储结果
        QMessageBox.information(self, "成功", "题目顺序已保存为新版本")
        self.accept()


class PaperPreviewDialog2(QDialog):
    def __init__(self, questions, parent=None):
        super().__init__(parent)
        self.questions = questions.copy()
        self.include_answers = True  # 新增属性，默认填充答案
        self.init_ui()
        self.load_data()

    def init_ui(self):
        self.setWindowTitle("试卷预览")
        self.setMinimumSize(800, 600)
        layout = QVBoxLayout()

        # 表格设置（调整为4列）
        self.table = QTableWidget()
        self.table.setColumnCount(4)
        self.table.setHorizontalHeaderLabels(["题目", "图片", "答案", "答案图"])

        # 列宽设置
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents)

        layout.addWidget(self.table)

        # 新增预览区域
        self.preview_area = QTextEdit()
        self.preview_area.setReadOnly(True)
        self.preview_area.setStyleSheet("font-size: 14px; background-color: #f9f9f9;")
        layout.addWidget(self.preview_area)

        # 新增是否填充答案的复选框
        self.include_answers_checkbox = QCheckBox("包含答案")
        self.include_answers_checkbox.setChecked(True)
        self.include_answers_checkbox.stateChanged.connect(self.toggle_include_answers)
        layout.addWidget(self.include_answers_checkbox)

        # 底部按钮（增加导出按钮）
        btn_box = QHBoxLayout()
        self.preview_btn = QPushButton("整体预览")
        self.preview_btn.clicked.connect(self.show_preview)
        self.export_btn = QPushButton("导出试卷")  # 新增导出按钮
        self.export_btn.clicked.connect(self.export_paper)  # 绑定导出逻辑
        self.cancel_btn = QPushButton("关闭")
        self.cancel_btn.clicked.connect(self.reject)
        btn_box.addStretch()
        btn_box.addWidget(self.preview_btn)
        btn_box.addWidget(self.export_btn)  # 添加导出按钮到布局
        btn_box.addWidget(self.cancel_btn)
        layout.addLayout(btn_box)
        self.setLayout(layout)

    def toggle_include_answers(self, state):
        """切换是否包含答案"""
        self.include_answers = state == Qt.Checked
        self.load_data()  # 重新加载数据以反映更改

    def load_data(self):
        self.table.setRowCount(len(self.questions))

        for row, q in enumerate(self.questions):
            # 题目内容
            self.table.setItem(row, 0, QTableWidgetItem(q['content']))

            # 题目图片（使用路径展示）
            if q['content_image']:
                label = QLabel()
                abs_path = os.path.join(os.getcwd(), q['content_image'])
                pixmap = QPixmap(abs_path)
                if not pixmap.isNull():
                    label.setPixmap(pixmap.scaled(200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation))
                self.table.setCellWidget(row, 1, label)

            # 答案（根据是否包含答案决定是否显示）
            if self.include_answers:
                self.table.setItem(row, 2, QTableWidgetItem(q['answer']))
            else:
                if q['question_type'] == "综合题":
                    # 综合题留出较大答题空间
                    self.table.setItem(row, 2, QTableWidgetItem("请在此处作答"))
                else:
                    self.table.setItem(row, 2, QTableWidgetItem(""))

            # 答案图片（使用路径展示）
            if q['answer_image']:
                label = QLabel()
                abs_path = os.path.join(os.getcwd(), q['answer_image'])
                pixmap = QPixmap(abs_path)
                if not pixmap.isNull():
                    label.setPixmap(pixmap.scaled(200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation))
                self.table.setCellWidget(row, 3, label)

    def show_preview(self):
        """显示整体预览（使用文件URL格式）"""
        preview_text = ""
        for idx, q in enumerate(self.questions, start=1):
            preview_text += f"<b>第 {idx} 题：</b><br>"
            preview_text += f"<b>题型：</b>{q['question_type']}<br>"
            preview_text += f"<b>题目：</b>{q['content']}<br>"

            if q['content_image']:
                abs_path = os.path.abspath(q['content_image'])
                file_url = QUrl.fromLocalFile(abs_path).toString()
                preview_text += f'<img src="{file_url}" width="200"><br>'

            # 根据是否包含答案决定是否显示答案
            if self.include_answers:
                preview_text += f"<b>答案：</b>{q['answer']}<br>"
            else:
                if q['question_type'] == "综合题":
                    preview_text += "<b>答案：</b><textarea style='width: 100%; height: 200px;' placeholder='请在此处作答'></textarea><br>"
                else:
                    preview_text += "<b>答案：</b><br>"

            if q['answer_image']:
                abs_path = os.path.abspath(q['answer_image'])
                file_url = QUrl.fromLocalFile(abs_path).toString()
                preview_text += f'<img src="{file_url}" width="200"><br>'

            preview_text += f"<b>分值：</b>{q['score']} 分<br><br>"

        self.preview_area.setHtml(preview_text)

    def export_paper(self):
        """导出试卷逻辑"""

        # 提示用户选择保存路径和文件名
        file_path, _ = QFileDialog.getSaveFileName(
            self, "导出试卷", "", "Word 文件 (*.docx);;Markdown 文件 (*.md);;PDF 文件 (*.pdf)"
        )
        if not file_path:
            return

        # 根据文件扩展名判断导出格式
        if file_path.endswith(".docx"):
            self.export_to_docx(file_path)
        elif file_path.endswith(".md"):
            self.export_to_markdown(file_path)
        elif file_path.endswith(".pdf"):
            self.export_to_pdf(file_path)

    def export_to_docx(self, file_path):
        """导出为 Word 格式"""
        doc = Document()
        for idx, q in enumerate(self.questions, start=1):
            doc.add_heading(f"第 {idx} 题", level=2)
            doc.add_paragraph(f"题型：{q['question_type']}")
            doc.add_paragraph(f"题目：{q['content']}")

            # 处理题目图片
            if q['content_image']:
                if isinstance(q['content_image'], QPixmap):
                    image = ImageQt(q['content_image'].toImage())
                    image.save("temp_content_image.png")
                    doc.add_picture("temp_content_image.png", width=Inches(3))
                else:
                    doc.add_picture(q['content_image'], width=Inches(3))

            # 根据是否包含答案决定是否显示答案
            if self.include_answers:
                doc.add_paragraph(f"答案：{q['answer']}")
            else:
                if q['question_type'] == "综合题":
                    doc.add_paragraph("答案：请在此处作答")
                else:
                    doc.add_paragraph("答案：")

            # 处理答案图片
            if q['answer_image']:
                if isinstance(q['answer_image'], QPixmap):
                    image = ImageQt(q['answer_image'].toImage())
                    image.save("temp_answer_image.png")
                    doc.add_picture("temp_answer_image.png", width=Inches(3))
                else:
                    doc.add_picture(q['answer_image'], width=Inches(3))

            doc.add_paragraph(f"分值：{q['score']} 分")
            doc.add_paragraph("\n")  # 添加换行

        doc.save(file_path)
        QMessageBox.information(self, "成功", f"试卷已导出为 Word 文件：{file_path}")

    def export_to_markdown(self, file_path):
        """导出为 Markdown 格式"""
        with open(file_path, "w", encoding="utf-8") as f:
            for idx, q in enumerate(self.questions, start=1):
                f.write(f"## 第 {idx} 题\n")
                f.write(f"**题型**：{q['question_type']}\n")
                f.write(f"**题目**：{q['content']}\n")

                # 处理题目图片
                if q['content_image']:
                    if isinstance(q['content_image'], QPixmap):
                        # 创建目标目录
                        img_dir = f"imgs/{q['id']}"
                        os.makedirs(img_dir, exist_ok=True)
                        img_filename = f"content_image_{idx}.png"
                        image = ImageQt(q['content_image'].toImage())
                        image.save(os.path.join(img_dir, img_filename))
                        f.write(f"![题目图片]({os.path.join(img_dir, img_filename)})\n")
                    else:
                        f.write(f"![题目图片]({q['content_image']})\n")

                # 根据是否包含答案决定是否显示答案
                if self.include_answers:
                    f.write(f"**答案**：{q['answer']}\n")
                else:
                    if q['question_type'] == "综合题":
                        f.write("**答案**：请在此处作答\n")
                    else:
                        f.write("**答案**：\n")

                # 处理答案图片
                if q['answer_image']:
                    if isinstance(q['answer_image'], QPixmap):
                        # 创建目标目录
                        img_dir = f"imgs/{q['id']}"
                        os.makedirs(img_dir, exist_ok=True)
                        img_filename = f"answer_image_{idx}.png"
                        image = ImageQt(q['answer_image'].toImage())
                        image.save(os.path.join(img_dir, img_filename))
                        f.write(f"![答案图片]({os.path.join(img_dir, img_filename)})\n")
                    else:
                        f.write(f"![答案图片]({q['answer_image']})\n")

                f.write(f"**分值**：{q['score']} 分\n\n")

        QMessageBox.information(self, "成功", f"试卷已导出为 Markdown 文件：{file_path}")

    def export_to_pdf(self, file_path):
        """导出为 PDF 格式"""
        from PyQt5.QtGui import QTextDocument
        from PyQt5.QtPrintSupport import QPrinter
        # 创建 QTextDocument 并填充内容
        doc = QTextDocument()
        html_content = ""
        for idx, q in enumerate(self.questions, start=1):
            html_content += f"<h2>第 {idx} 题</h2>"
            html_content += f"<p><b>题型：</b>{q['question_type']}</p>"
            html_content += f"<p><b>题目：</b>{q['content']}</p>"

            # 处理题目图片
            if q['content_image']:
                if isinstance(q['content_image'], QPixmap):
                    image = ImageQt(q['content_image'].toImage())
                    image.save("temp_content_image.png")
                    html_content += f'<img src="temp_content_image.png" width="300">'
                else:
                    html_content += f'<img src="{q["content_image"]}" width="300">'

            # 根据是否包含答案决定是否显示答案
            if self.include_answers:
                html_content += f"<p><b>答案：</b>{q['answer']}</p>"
            else:
                if q['question_type'] == "综合题":
                    html_content += "<p><b>答案：</b><textarea style='width: 100%; height: 200px;' placeholder='请在此处作答'></textarea></p>"
                else:
                    html_content += "<p><b>答案：</b></p>"

            # 处理答案图片
            if q['answer_image']:
                if isinstance(q['answer_image'], QPixmap):
                    image = ImageQt(q['answer_image'].toImage())
                    image.save("temp_answer_image.png")
                    html_content += f'<img src="temp_answer_image.png" width="300">'
                else:
                    html_content += f'<img src="{q["answer_image"]}" width="300">'

            html_content += f"<p><b>分值：</b>{q['score']} 分</p>"
            html_content += "<p>&nbsp;</p>"  # 添加换行
        doc.setHtml(html_content)
        # 导出为 PDF
        printer = QPrinter(QPrinter.HighResolution)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setOutputFileName(file_path)
        doc.print_(printer)

        QMessageBox.information(self, "成功", f"试卷已导出为 PDF 文件：{file_path}")


# 在文件顶部导入新增组件
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QFormLayout, QLineEdit, QDialogButtonBox


# 新增试卷配置对话框
class ExamConfigDialog(QDialog):
    def __init__(self, question_types, parent=None):
        super().__init__(parent)
        self.setWindowTitle("试卷配置")
        self.setMinimumWidth(300)

        layout = QVBoxLayout()
        form_layout = QFormLayout()

        # 试卷名称输入
        self.name_input = QLineEdit("期末试卷")
        form_layout.addRow("试卷名称：", self.name_input)

        # 题型分数配置
        self.type_scores = {}
        for t in question_types:
            spin = QSpinBox()
            spin.setRange(1, 100)
            spin.setValue(10)  # 默认分数
            self.type_scores[t] = spin
            form_layout.addRow(f"{t}分数：", spin)

        # 操作按钮
        self.btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.btn_box.accepted.connect(self.accept)
        self.btn_box.rejected.connect(self.reject)

        layout.addLayout(form_layout)
        layout.addWidget(self.btn_box)
        self.setLayout(layout)
